package cn.edu.cdtu.healthclient.activity.fragment;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cn.edu.cdtu.healthclient.activity.MainActivity;
import cn.edu.cdtu.healthclient.domain.NewsFromInternet;
import cn.edu.cdtu.healthclient.utils.ConnectUtil;
import cn.edu.scu.healthclient.activity.R;

public class MainActivityHealthNewsFragmentOutFragment extends Fragment
{
	private View mainView;
	private static ArrayList<HashMap<String,Object>> newslist;
	private static SimpleAdapter simpleAdapter;
	private Handler handler;
	private ListView newsFromBaidu;
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = getActivity().getLayoutInflater();
		mainView = inflater.inflate(R.layout.activity_main_healthnews_fragment_out_fragment, (ViewGroup)getActivity().findViewById(R.id.viewPager), false);
		
		newsFromBaidu= (ListView) mainView.findViewById(R.id.NewsFromBaidu);
		newslist=new ArrayList<HashMap<String, Object>>();
		simpleAdapter=new SimpleAdapter
		(
			getActivity(),
			newslist,
			R.layout.activity_main_healthnews_fragment_out_fragment_outstyle,
			new String[]{"title", "pubDate", "description","link"},
			new int[]{R.id.BaiduNews_title, R.id.BaiduNews_pubDate, R.id.BaiduNews_description, R.id.BaiduNews_link}
		);
		
		newsFromBaidu.setAdapter(simpleAdapter);
		((MainActivity)getActivity()).getTaskQueue().addTask(
				new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				BaiduNewsAsyncTask baiduNewsAsyncTask = new BaiduNewsAsyncTask();
				baiduNewsAsyncTask.execute(
						ConnectUtil.HealthServerContect.SERVER_URL
						+ ConnectUtil.HealthServerContect.NEWS_XML);
			}
		}));
		handler = new MyHandler();
	    
	    newsFromBaidu.setOnItemClickListener
	    (
	    	new OnItemClickListener()
	    	{

				public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
				{
					TextView BaiduNewsLink = (TextView) mainView.findViewById(R.id.BaiduNews_link);	
					Intent intent = new Intent();
					intent.setAction("android.intent.action.VIEW"); 
					Uri content_url = Uri.parse(BaiduNewsLink.getText().toString());   
					intent.setData(content_url);  
				    startActivity(intent);
				}
	       }
	   );
		
	}
	
	private static class MyHandler extends Handler{

		/* (non-Javadoc)
		 * <p>Title: handleMessage</p> 
		 * <p>Description: </p> 
		 * @param msg 
		 * @see android.os.Handler#handleMessage(android.os.Message)
		 */
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if(msg.obj != null) 
       		{
       			NewsFromInternet newsFromInternet = (NewsFromInternet)msg.obj;
	    		HashMap<String, Object> map = new HashMap<String, Object>();
	    		map.put("title", newsFromInternet.getTitle());
	    		map.put("pubDate", newsFromInternet.getPubDate());
	    		map.put("description",newsFromInternet.getDescription());
	    		map.put("link", newsFromInternet.getLink());
	    		newslist.add(map);
	    		simpleAdapter.notifyDataSetChanged();
       		}
		}
		
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
	{
		ViewGroup viewGroup = (ViewGroup) mainView.getParent(); 
        if (viewGroup!= null) 
        { 
        	viewGroup .removeAllViewsInLayout(); 
            Log.v("ali", "移除已存在的View3");
        } 
		return mainView;
	}
	
	private class NewsHandler extends DefaultHandler 
	{
	   	private NewsFromInternet internetNews;
	   	private String content;
	   	
	   	public void startElement(String uri, String localName, String name, org.xml.sax.Attributes attributes) throws SAXException 
	   	{
	   		if(localName.equals("news")) 
	   		{
	   			internetNews = new NewsFromInternet();
	   		} 
	   			super.startElement(uri, localName, name, attributes);
	   	}
	   		
	   	public void characters (char[] ch, int start, int length)  throws SAXException
	   	{
	   	   	content = new String(ch, start, length);
	   	   	super.characters(ch, start, length);
	   	}
	   	
	   	public void endElement(String uri, String localName, String name) throws SAXException
	   	{
	   		if(localName.equals("news")) 
	   		{
		   		Message msg = handler.obtainMessage();
		   		msg.obj = internetNews;
		   		handler.sendMessage(msg);
	   		}
	   		else if(localName.equals("title")) 
	   		{
	   			internetNews.setTitle(content);
	   		}
	   		else if(localName.equals("description")) 
	   		{
	   			internetNews.setDescription(content);
	   		} 
	   		else if(localName.equals("link")) 
	   		{
	   			internetNews.setLink(content);
	   		} 
	   		else if(localName.equals("pubDate")) 
	   		{
	   			internetNews.setPubDate(content);
		   	}
	   		super.endElement(uri, localName, name);
	   	}
	}

	
	private class BaiduNewsAsyncTask extends AsyncTask<String, Integer, String> 
	{
		protected String doInBackground(String... params) 
		{
			HttpGet httpGet = new HttpGet(params[0]);
			HttpClient httpclient = ((MainActivity)getActivity()).getBinder().getHttpClient();
			try 
			{
				HttpResponse httpResponse = httpclient.execute(httpGet);
				if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
				{
					HttpEntity HttpEntitiy = httpResponse.getEntity();
					InputStream in = HttpEntitiy.getContent();
					InputSource inputSource = new InputSource(in);
					SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
					XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
					xmlReader.setContentHandler(new NewsHandler());
					xmlReader.parse(inputSource);
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}
	}
}
